package com.yami.shop.api.controller;

import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.app.param.PayGasUserParam;
import com.yami.shop.bean.app.param.PayUserParam;
import com.yami.shop.bean.enums.PayEntry;
import com.yami.shop.bean.model.Blockchain;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.pay.PayInfoDto;
import com.yami.shop.bean.vo.NftPlatformVO;
import com.yami.shop.common.bean.PageDTO;
import com.yami.shop.common.bean.PageVO;
import com.yami.shop.common.enums.PayType;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.RedisUtil;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.manager.impl.PayManager;
import com.yami.shop.nft.common.model.NftGasDeploy;
import com.yami.shop.nft.common.model.NftRechargeActivity;
import com.yami.shop.nft.common.service.NftGasDeployService;
import com.yami.shop.nft.common.service.NftRechargeActivityService;
import com.yami.shop.security.api.model.YamiUser;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.security.common.manager.PasswordManager;
import com.yami.shop.service.BlockchainService;
import com.yami.shop.service.PayInfoService;
import com.yami.shop.service.UserService;
import com.yami.shop.user.common.model.UserGasInfo;
import com.yami.shop.user.common.model.UserGasLog;
import com.yami.shop.user.common.service.UserGasInfoService;
import com.yami.shop.user.common.service.UserGasLogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Tag(name = "GAS充值支付接口")
@RestController
@RequestMapping("/p/gasNft")
@AllArgsConstructor
public class PayGasNftController {
    /**
     * 会员信息
     */
    private final UserGasLogService userGasLogService;
    private final Snowflake snowflake;
    private final PayManager payManager;
    private final PayInfoService payInfoService;
    private final NftGasDeployService nftGasDeployService;
    private final NftRechargeActivityService nftRechargeActivityService;
    private final ShopConfig shopConfig;
    private final PasswordEncoder passwordEncoder;
    private final PasswordManager passwordManager;
    private final UserService userService;
    private final UserGasInfoService userGasInfoService;
    public static final int SYS_MONEY_UNIT = 100;

    /**
     * GAS充值支付接口
     */
    @PostMapping("/payGas")
    @Operation(summary =  "GAS充值接口", description = "GAS充值接口")
    @SneakyThrows
    public ServerResponseEntity<?> payGas(HttpServletResponse httpResponse, @RequestBody PayGasUserParam PayGasUserParam) {
        YamiUser user = SecurityUtils.getUser();
        if (!user.getEnabled()) {
            // 您已被禁用，不能购买，请联系平台客服
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.order.pay.user.disable"));
        }
        if (PayGasUserParam.getPayType().equals(PayType.SCOREPAY.value())){
            // 请使用微信或支付宝进行支付
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.user.payType.error"));
        }
        //充值能量选项
        NftGasDeploy gasListById = nftGasDeployService.getGasListById(PayGasUserParam.getDeployId());
        if (Objects.isNull(gasListById)) {
            // 当前余额充值选项已被删除
            throw new YamiShopBindException("yami.user.blance.not.exist");
        }
        if(StringUtils.isEmpty(RedisUtil.get("channelCode::"+ user.getUserId()))){
            throw new YamiShopBindException("yami.chain.getcheck.fail");
        }
        if(PayGasUserParam.getPayType().equals(PayType.BALANCE.value())){
            String decryptPassword = passwordManager.decryptPassword(PayGasUserParam.getPassword());
            User userData = userService.getById(user.getUserId());
            if (!passwordEncoder.matches(decryptPassword, userData.getPayPassword())) {
                return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.dtc.password.check"));
            }
        }

        // 使用雪花算法生成支付单号
        String payNo = String.valueOf(snowflake.nextId());
        Date now = new Date();
        //生成GAS余额充值日志
        UserGasLog userGasLog = new UserGasLog();
        userGasLog.setCreateTime(now);
        userGasLog.setIoType(1); // 收支类型 0支出 1收入
        userGasLog.setType(1);   // gas 充值类型
        userGasLog.setIsPayed(0);  // 0未支付
        userGasLog.setPayNo(payNo);  // 支付单号
        userGasLog.setUserId(user.getUserId());
        userGasLog.setGasId(Long.valueOf(PayGasUserParam.getDeployId()));  //gas id
        BigDecimal money = new BigDecimal(gasListById.getNftSpecialPrice()).divide(new BigDecimal(SYS_MONEY_UNIT));
        money = money.setScale(2, BigDecimal.ROUND_HALF_UP);
        userGasLog.setGasBalance(money.doubleValue());
        userGasLog.setTabStatus(0); //默认0未发送
        userGasLog.setGasNum(gasListById.getNftNum());
        userGasLogService.save(userGasLog);

        PayUserParam payUserParam = new PayUserParam();
        payUserParam.setNeedAmount(userGasLog.getGasBalance());
        payUserParam.setPayNo(payNo);
        payUserParam.setOrderIds(userGasLog.getGasLogId());
        payUserParam.setPayType(PayGasUserParam.getPayType());

        PayInfoDto payInfo = payInfoService.payGas(user.getUserId(), payUserParam);
        payInfo.setBizUserId(user.getBizUserId());
        payInfo.setPayType(PayGasUserParam.getPayType());
        payInfo.setApiNoticeUrl("/notice/pay/" + PayEntry.GAS_RECHARGE.value() + "/" + PayGasUserParam.getPayType());
        payInfo.setReturnUrl(PayGasUserParam.getReturnUrl());
        payInfo.setPayUserId(user.getXsUserId());
        payInfo.setReceiveUserId(shopConfig.getHnaPay().getMerId());
        payInfo.setXsFastPaymentOneParam(PayGasUserParam.getXsFastPaymentOneParam());
        payInfo.setPayUserType("0"); // 用户购买
        return payManager.doPay(httpResponse, payInfo);
    }

    /**
     * GAS 能量活动领取接口
     */
    @GetMapping("/activityGas")
    @Operation(summary =  "GAS活动领取接口", description = "GAS活动领取接口")
    @Transactional
    public ServerResponseEntity<?> activityGas() {
        YamiUser user = SecurityUtils.getUser();
        if (!user.getEnabled()) {
            // 您已被禁用，不能购买，请联系平台客服
            return ServerResponseEntity.showFailMsg(I18nMessage.getMessage("yami.order.pay.user.disable"));
        }
        // 能量领取不校验链信息
//        if(StringUtils.isEmpty(RedisUtil.get("channelCode::"+ user.getUserId()))){
//            throw new YamiShopBindException("yami.chain.getcheck.fail");
//        }
        //获取当前活动id
        NftRechargeActivity nftRechargeActivity = nftRechargeActivityService.getOne(new LambdaQueryWrapper<NftRechargeActivity>().eq(NftRechargeActivity::getStatus, 1));
        // 使用雪花算法生成支付单号
        String payNo = String.valueOf(snowflake.nextId());
        Date now = new Date();
        //生成GAS余额充值日志
        UserGasLog userGasLog = new UserGasLog();
        userGasLog.setCreateTime(now);
        userGasLog.setIoType(1); // 收支类型 0支出 1收入
        userGasLog.setType(2);   // gas 领取
        userGasLog.setIsPayed(1);  // 0未支付 1 已支付
        userGasLog.setPayNo(payNo);  // 支付单号
        userGasLog.setUserId(user.getUserId());
        userGasLog.setGasId(Long.valueOf(nftRechargeActivity.getId()));  //gas id
        userGasLog.setGasBalance(0.00);
        userGasLog.setTabStatus(0); //默认0未发送
        userGasLog.setGasNum(nftRechargeActivity.getActivityNum());
        userGasLogService.save(userGasLog);
        // 添加用户gas 余额
        LambdaQueryWrapper<UserGasInfo> eq = new LambdaQueryWrapper<UserGasInfo>().eq(UserGasInfo::getUserId, userGasLog.getUserId());
        UserGasInfo userGasInfo = userGasInfoService.getOne(eq);
        if(ObjectUtils.isNotEmpty(userGasInfo)){
            userGasInfo.setGasNumber(userGasInfo.getGasNumber()+nftRechargeActivity.getActivityNum());
            userGasInfoService.updateById(userGasInfo);
        }else{
            userGasInfo = new UserGasInfo();
            userGasInfo.setGasNumber(userGasLog.getGasNum());
            userGasInfo.setUserId(userGasLog.getUserId());
            userGasInfoService.save(userGasInfo);
        }
        return ServerResponseEntity.success();
    }

    @GetMapping("/getShowGas")
    @Operation(summary =  "查询是否可以领取", description = "查询是否可以领取")
    public ServerResponseEntity<Map<String,Object>> getShowGas() {
        Map<String,Object> map = new HashMap<>();
        YamiUser user = SecurityUtils.getUser();
        NftRechargeActivity nftRechargeActivity = nftRechargeActivityService.getOne(new LambdaQueryWrapper<NftRechargeActivity>().eq(NftRechargeActivity::getStatus, 1));
        if(ObjectUtils.isNotEmpty(nftRechargeActivity)){
            UserGasLog one = userGasLogService.getOne(
                    new LambdaQueryWrapper<UserGasLog>()
                            .eq(UserGasLog::getUserId, user.getUserId())
                            .eq(UserGasLog::getGasId, nftRechargeActivity.getId())
                            .eq(UserGasLog::getType, 2).last("limit 1")
            );
            if(ObjectUtils.isEmpty(one)){
                map.put("isReceive", true);
                map.put("gasNum",nftRechargeActivity.getActivityNum());
            }else{
                map.put("isReceive", false);
                map.put("gasNum",nftRechargeActivity.getActivityNum());
            }
        }else{
            // 0 暂无活动
            map.put("isReceive", true);
            map.put("gasNum",0);
        }
        return ServerResponseEntity.success(map);
    }

    @GetMapping("/getGasDeployList")
    @Operation(summary = "前端能量充值配置列表", description = "前端能量充值配置列表")
    public ServerResponseEntity<List<NftGasDeploy>> getGasDeployList() {
        return ServerResponseEntity.success(nftGasDeployService.getGasDeployList());
    }

    @GetMapping("/getGasDetailed")
    @Operation(summary = "前端查询明细", description = "前端查询明细")
    public ServerResponseEntity<PageVO<UserGasLog>> getGasDetailed(PageDTO pageDTO, @RequestParam("year") String year,@RequestParam("month")  String month) {
        YamiUser user = SecurityUtils.getUser();
        return ServerResponseEntity.success(userGasLogService.getGasDetailed(pageDTO,year,month,user.getUserId()));
    }

    @GetMapping("/isPay")
    @Operation(summary =  "获取购买gas支付信息", description = "获取购买gas支付信息")
    public ServerResponseEntity<Map<String,Object>> isPay(){
        YamiUser user = SecurityUtils.getUser();
        UserGasLog userGasLog = userGasLogService.getGasPayInfoByUserId(user.getUserId());
        Map<String,Object> map = new HashMap<>();
        map.put("isPayed",userGasLog.getIsPayed());
        map.put("payTime",userGasLog.getUpdateTime());
        return ServerResponseEntity.success(map);
    }

    @GetMapping("/getUserNumberByuserId")
    @Operation(summary =  "获取用户得能量值", description = "获取用户得能量值")
    public ServerResponseEntity<UserGasInfo> getUserNumberByuserId(){
        YamiUser user = SecurityUtils.getUser();
        LambdaQueryWrapper<UserGasInfo> eq = new LambdaQueryWrapper<UserGasInfo>().eq(UserGasInfo::getUserId, user.getUserId());
        UserGasInfo userGasInfo = userGasInfoService.getOne(eq);
        return ServerResponseEntity.success(userGasInfo);
    }
}
